package org.jtzc.chat.controller;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author wu chuang
 * @description
 */
@RestController
public class ChatContextContrller {

    @Autowired
    private ChatModel chatModel;

    private final String systemPrompt = "你现在是一个语言学习辅助助手.";
    private int maxLen = 3;
    private List<Message> historyMessage = new ArrayList<>(List.of(new SystemMessage(systemPrompt)));

    @GetMapping("noContext")
    public String noContext(@RequestParam("msg")String msg) {
        return chatModel.call(msg);
    }

    @GetMapping("/context")
    public String context(@RequestParam("msg")String msg) {
        historyMessage.add(new UserMessage(msg));
        if (historyMessage.size() > maxLen) {
            historyMessage = historyMessage.subList(historyMessage.size() - maxLen - 1, historyMessage.size());
        }
        ChatResponse chatResponse = chatModel.call(new Prompt(historyMessage));
        AssistantMessage assistantMessage = chatResponse.getResult().getOutput();
        historyMessage.add(assistantMessage);
        return assistantMessage.getContent();
    }
}
